#include <stdio.h>
#include <string.h>
#include <windows.h>
#include "memfile.h"

MEMFILE *memfopen (const char* filename, const char* mode)
{
    int isrc = 0;
    char* path;
    char* rctype = NULL;
    char* rcname = NULL;

    if (!filename) return NULL;
    path = strdup(filename);

    rctype = strtok(path, ":");
    rcname = strtok(NULL, "");
    if (rctype && rcname) {
        isrc = 1;
    }

    void* filep = NULL;

    if (isrc) {
        HRSRC hres = FindResourceA(NULL, rcname, rctype);
        if (hres) {
            HGLOBAL hrc = LoadResource(NULL, hres);
            //*rclen = SizeofResource(NULL, hres);
            filep = LockResource(hrc);
        }
    }
    else {
        filep = fopen(path, mode);
    }

    free(path);

    if (!filep)
        return NULL;

    MEMFILE* mf = (MEMFILE*)malloc(sizeof(MEMFILE));
    mf->isfile = !isrc;
    mf->filep = filep;

    return mf;
}

void memfread(void* data, int size, MEMFILE *f)
{
    if (f->isfile)
        fread(data, 1, size, f->filep);
    else {
        memcpy(data, f->filep, size);
        f->filep += size;
    }
}

void memfclose(MEMFILE *f)
{
    if (!f) return;

    if (f->isfile)
        fclose((FILE*)f->filep);
    else
        free(f->filep);
}
